# -*- coding : utf_8 -*-
'''
=======================================
Time : 2025/3/14 10:27
Author : 田霄汉
Email : 522989570@qq.com
File : conftest.py
Project : pytest_demo
=======================================
'''
from datetime import timedelta
import time

import allure
import pytest
from selenium import webdriver
from config import setting
from utils.dingrobot_util import DingrobotUtil
from utils.yaml_util import YamlUtil
# driver = webdriver.Chrome()


@pytest.fixture()
def conn_database():
    print("连接数据库成功")
    yield
    print("关闭数据库成功")


@pytest.fixture(scope="session", autouse=False)
def clear_extract(yaml_name="../extract.yml"):
    YamlUtil().clear_yaml(yaml_name=yaml_name)


def format_runtime(seconds):
    """将秒转换成时分秒格式"""
    return str(timedelta(seconds=seconds)).split('.')[0]


# @pytest.hookimpl(tryfirst=True, hookwrapper=True)
# def pytest_runtest_makereport():
#     """pytest预定的钩子函数，用来对失败的测试用例进行截图"""
#     outcome = yield
#     result = outcome.get_result()
#     if result.when == 'call':
#         xfail = hasattr(result, 'wasxfail')
#         if (result.skipped and xfail) or (result.failed and not xfail):
#             with allure.step('测试用例失败截图'):
#                 allure.attach(driver.get_screenshot_as_png(), '失败截图', attachment_type=allure.attachment_type.PNG)


# @pytest.hookimpl(hookwrapper=True)
def pytest_terminal_summary(terminalreporter):
    """pytest预定的钩子函数，用于自动收集测试结果"""
    # 收集测试用例总数
    total = terminalreporter._numcollected
    # 分别获取passed,failed,error,skipped测试用例的数量
    passed = len(terminalreporter.stats.get('passed', []))
    failed = len(terminalreporter.stats.get('failed', []))
    error = len(terminalreporter.stats.get('error', []))
    skipped = len(terminalreporter.stats.get('skipped', []))
    # round()作用是保留2为小数
    runtime = round(time.time() - terminalreporter._sessionstarttime, 2)
    # 将秒转换成时分秒格式
    formatted_time = format_runtime(runtime)

    summary = f'''
    ========================================
    自动化测试结果，通知如下，具体执行结果：
    测试用例总数：{total}；
    通过测试用例数：{passed}；
    失败测试用例通过数：{failed}；
    报错测试用例数：{error}；
    跳过测试用例数：{skipped}；
    总运行时长：{runtime}s ({formatted_time})；
    ========================================'''
    # 判断setting文件中is_dd_send是否发送钉钉群
    if setting.is_dd_send:
        # 测试执行结果发送到钉钉群
        DingrobotUtil().send_dd_msg(content=summary, at_all=setting.is_at_all)